<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <!-- 使数字字符串变为数值：字符串 减去 数值（0） -->
      <el-steps :active="activeStep - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form
        :model="addGoodsForm"
        :rules="goodsFormRules"
        ref="addGoodsFormRef"
        label-position="top"
      >
        <!-- 标签页区域 -->
        <el-tabs
          v-model="activeStep"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="categoriesList"
                :props="cascaderProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染动态参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyDataList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="val"
                  v-for="(val, index) in item.attr_vals"
                  :key="index"
                  border=""
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyDataList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="addGoods" class="addGoddsBtn"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览区域 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
      <img :src="previewUrl" alt="预览" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'AddGoods',
  data() {
    return {
      // 通过这个值，进行步骤条和标签页联动
      activeStep: '0',
      //   添加商品的表单数据
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 存放图片的临时URL
        pics: [],
        // 商品的详情描述
        goods_introduce: '',
        // 存放商品的参数
        attrs: [],
      },
      // 添加商品的表单规则
      goodsFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品的名称',
            trigger: ['blur', 'change'],
          },
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品的价格',
            trigger: ['blur', 'change'],
          },
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品的重量',
            trigger: ['blur', 'change'],
          },
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品的数量',
            trigger: ['blur', 'change'],
          },
        ],
        goods_cat: [
          {
            required: true,
            message: '请输入商品的分类',
            trigger: ['blur', 'change'],
          },
        ],
      },
      //   父级分类的列表
      categoriesList: [],
      //   指定级联选择器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      //   动态参数列表
      manyDataList: [],
      // 静态属性列表
      onlyDataList: [],
      // 上传图片的地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 为上传图片添加token
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      // 图片预览的url
      previewUrl: '',
      // 显示对话框的显示与隐藏
      previewDialogVisible: false,
    }
  },
  methods: {
    // 获取分类数据列表
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.categoriesList = res.data
    },
    handleChange() {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.warning('请填写商品的基本信息')
        return false
      }
    },
    async tabClicked() {
      // 如果activeStep是1的话，就是访问到了动态参数的面板
      // 如果activeStep是2的话，就是访问到了静态属性的面板
      if (this.activeStep === '1') {
        //   发送网络请求
        const { data: res } = await this.$http.get(
          `categories/${this.categoriesId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        // 将attr_vals的字符串形式转数组形式
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        })
        this.manyDataList = res.data
      } else if (this.activeStep === '2') {
        //   发送网络请求
        const { data: res } = await this.$http.get(
          `categories/${this.categoriesId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        this.onlyDataList = res.data
        console.log(this.onlyDataList)
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 处理移出图片的操作
    handleRemove(file) {
      // 获取到图片的临时路径
      const filePath = file.response.data.tmp_path
      // 通过临时路径获取到在pics中的索引
      const index = this.addGoodsForm.pics.findIndex((x) => x == filePath)
      // 将临时路径从pics数组中删除
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 处理图片上传完毕事件
    handleSuccess(response) {
      const picInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods() {
      // 监测表单的预校验
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项')
        // 因为级联选择器的goods_cat是需要数组的，而发送网络请求的的是需要字符串的，所以对addGoodsForm进行深拷贝
        // lodash 中 cloneDeep(obj)
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        //  处理动态参数
        this.manyDataList.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(','),
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyDataList.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        form.attrs = this.addGoodsForm.attrs
        
        // 发送请求添加商品，商品名必须唯一
        const {data: res} = await this.$http.post('goods', form)
        if(res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    },
  },
  created() {
    this.getCategoriesList()
  },
  computed: {
    // 当前选中的三级分类id
    categoriesId() {
      return this.addGoodsForm.goods_cat.length
        ? this.addGoodsForm.goods_cat[2]
        : null
    },
  },
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0;
}

.previewImg {
  width: 100%;
}

.addGoddsBtn {
  margin-top: 20px;
}
</style>